package common_rpc

import (
	"context"
	"gitee.com/xlizy/common-go/base/enums/common_error"
	"gitee.com/xlizy/common-go/base/response"
	"gitee.com/xlizy/common-go/utils/zlog"
	"gitee.com/xlizy/rpc-interface/rpc_pbs"
	"time"
)

var (
	CtxOptionsTimeOut = "timeout"
	CtxOptionsShowLog = "showLog"
)

func R(rpcResult *rpc_pbs.RpcResult, err error) *response.Response {
	if err != nil {
		zlog.Error("Rpc接口异常信息:{}", err.Error())
		return response.Error(common_error.RpcCallError, nil)
	}
	res := &response.Response{}
	res.Success = rpcResult.Success
	res.Code = rpcResult.Code
	res.Msg = rpcResult.Msg
	res.ResponseTime = rpcResult.ResponseTime
	res.TraceId = rpcResult.TraceId
	if rpcResult.Code == common_error.RequestArgumentNotValid.Code() {
		var data rpc_pbs.InvalidParams
		if e := rpcResult.Data.UnmarshalTo(&data); e == nil {
			res.Data = data.Items
		} else {
		}
		return res
	}
	res.Data = rpcResult.Data
	return res
}

func CustomCtx(options map[string]any) context.Context {
	finalCtx := context.TODO()
	finalCtx = context.WithValue(finalCtx, CtxOptionsTimeOut, 30*time.Second)
	finalCtx = context.WithValue(finalCtx, CtxOptionsShowLog, true)
	if len(options) > 0 {
		for k, v := range options {
			finalCtx = context.WithValue(finalCtx, k, v)
		}
	}
	return finalCtx
}

func DefaultCtx() context.Context {
	parent := context.TODO()
	return context.WithValue(parent, CtxOptionsTimeOut, 30*time.Second)
}
